package com.bdqn.easybuy1.dao.impl;

import com.bdqn.easybuy1.dao.BaseDao;
import com.bdqn.easybuy1.dao.OrderDetailDao;
import com.bdqn.easybuy1.entities.OrderDetail;
import com.bdqn.easybuy1.param.OrderDetailParam;
import com.bdqn.easybuy1.utils.EmptyUtils;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailDaoImpl extends BaseDao<OrderDetail> implements OrderDetailDao {
    /**
     * 插入一条订单详情
     *
     * @param conn   数据库连接对象
     * @param detail 封装数据的对象
     * @return 返回受影响行数
     * @throws Exception
     */
    @Override
    public int insert(Connection conn, OrderDetail detail) throws Exception {
        // 如何自定获取插入的ID
        String sql = "INSERT INTO `easybuy_order_detail`(`orderId`,`productId`,`quantity`,`cost`) VALUES (?,?,?,?)";
        return this.update(conn, sql, detail.getOrderId(),
                detail.getProduct().getId(),
                detail.getQuantity(),
                detail.getCost());
    }

    /**
     * 删除订单详情
     *
     * @param conn   数据库连接对象
     * @param detail 封装删除条件的对象
     * @return 返回受影响行数
     * @throws Exception
     */
    @Override
    public int deleteById(Connection conn, OrderDetail detail) throws Exception {
        String sql = " DELETE FROM `easybuy_order_detail` WHERE `id` = ? ";
        return this.update(conn, sql, detail.getId());
    }

    /**
     * 根据id获取订单详情
     *
     * @param conn 数据库连接对象
     * @param id   订单id
     * @return 返回订单详情对象
     * @throws Exception
     */
    @Override
    public OrderDetail getOrderDetailById(Connection conn, Integer id) throws Exception {
        String sql = "SELECT `orderId`,`productId`,`quantity`,`cost` FROM `easybuy_order_detail` WHERE `id` = ?";
        return super.getBean(conn, sql, id);
    }

    /**
     * 根据订单id查询改订单所有的订单详情
     *
     * @param conn    数据库连接对象
     * @param orderId 订单id
     * @return 返回订单详情列表
     * @throws Exception
     */
    @Override
    public List<OrderDetail> getOrderDetailList(Connection conn, Integer orderId) throws Exception {
        String sql = "SELECT `id`,`orderId`,`productId`,`quantity`,`cost` FROM `easybuy_order_detail` WHERE 1=1";

        List<Object> objParams = new ArrayList<>();

        StringBuilder sb = new StringBuilder(sql);

        if (EmptyUtils.isNotEmpty(orderId)) {
            sb.append(" AND `orderId` = ? ");
            objParams.add(orderId);
        }

        return super.getBeanList(conn, sb.toString(), objParams.toArray());
    }

    /**
     * 根据条件查询订单详情的数量
     *
     * @param conn   数据库连接对象
     * @param params 查询参数
     * @return 返回数据条数
     * @throws Exception
     */
    @Override
    public Integer queryOrderDetailCount(Connection conn, OrderDetailParam params) throws Exception {
        String sql = "SELECT count(*) FROM `easybuy_order_detail`";
        return super.getValue(conn, sql);
    }
}
